import cv2

# 加载Haar级联检测器
face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
# eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
eye_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml"
)


# 打开摄像头
cap = cv2.VideoCapture(1)

while True:
    # 读取一帧图像
    ret, frame = cap.read()

    # 读取一张图片
    # imgPath = "./demo.jpg"
    # imgOutPath = "./demo_out.jpg"
    # frame = cv2.imread(imgPath)

    # 将图像转换为灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, 1.2, 5)

    # 对每张检测到的人脸进行处理
    for x, y, w, h in faces:
        # 在人脸周围绘制矩形
        cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

        # 获取人脸区域
        roi_gray = gray[y : y + h, x : x + w]
        roi_color = frame[y : y + h, x : x + w]

        # 检测眼睛
        # eyes = eye_cascade.detectMultiScale(
        #     roi_gray, 1.5, 6, flags=cv2.CASCADE_DO_CANNY_PRUNING
        # )
        eyes = eye_cascade.detectMultiScale(
            roi_gray,
            1.3,
            6,
            minSize=(80, 80),
            maxSize=(140, 140),
            # scaleFactor=1.1,
            # minNeighbors=5,
            # minSize=(30, 30),
        )

        # 对每只眼睛进行处理
        for ex, ey, ew, eh in eyes:
            # 在眼睛周围绘制矩形
            cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)

            # 获取眼睛区域
            eye_region = roi_gray[ey : ey + eh, ex : ex + ew]

            # 使用简单的阈值分割来寻找瞳孔
            _, thresh = cv2.threshold(eye_region, 40, 255, cv2.THRESH_BINARY)

            # 寻找瞳孔轮廓
            contours, _ = cv2.findContours(
                thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
            )

            # 如果找到了轮廓
            if contours:
                # 寻找最大的轮廓（即瞳孔）
                pupil = max(contours, key=cv2.contourArea)

                # 寻找瞳孔中心
                M = cv2.moments(pupil)
                if M["m00"] != 0:
                    cx = int(M["m10"] / M["m00"]) + ex + x
                    cy = int(M["m01"] / M["m00"]) + ey + y

                    # 在图像上绘制瞳孔中心
                    cv2.circle(frame, (cx, cy), 3, (0, 255, 0), -1)

                    # 根据瞳孔位置确定方向
                    if cx < (x + ex + (4 * ew // 10)):
                        direction = "Left"
                    # elif cx > (x + ex + 2 * ew // 3):
                    elif cx > (x + ex + (6 * ew // 10)):
                        direction = "Right"
                    else:
                        direction = "Center"
                    print(cx, x + ex, (x + ex + ew), direction)

                    # 在图像上显示方向信息
                    cv2.putText(
                        frame,
                        direction,
                        (x + ex, y + ey - 10),
                        cv2.FONT_HERSHEY_SIMPLEX,
                        0.5,
                        (0, 0, 255),
                        2,
                    )
            # # 计算眼睛中心坐标
            # eye_center_x = x + ex + ew // 2
            # eye_center_y = y + ey + eh // 2

            # # 根据眼睛位置确定方向
            # if eye_center_x < w // 3:
            #     direction = "Left"
            # elif eye_center_x > 2 * w // 3:
            #     direction = "Right"
            # else:
            #     direction = "Center"

            # # 在图像上显示方向信息
            # cv2.putText(
            #     frame,
            #     direction,
            #     (eye_center_x, eye_center_y - 40),
            #     cv2.FONT_HERSHEY_SIMPLEX,
            #     0.5,
            #     (0, 0, 255),
            #     2,
            # )

    # 显示结果图像
    cv2.imshow("Eye Direction Detection", frame)
    # cv2.imwrite(imgOutPath, frame)
    # 按下q键退出循环
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# # 释放摄像头并关闭窗口
# cap.release()
# cv2.destroyAllWindows()
